package com
{
	import com.org.as3wavsound.WavSound;
	import com.org.bytearray.micrecorder.encoder.WaveEncoder;
	import com.org.bytearray.micrecorder.events.RecordingEvent;
	import com.org.bytearray.micrecorder.MicRecorder;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.media.Microphone;
	import flash.net.FileReference;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	
	
	[SWF(width="320", height="200", frameRate="31", backgroundColor="#FFFFFF")]
	public class TestRecorder extends Sprite
	{
		private var recorder:MicRecorder = new MicRecorder( new WaveEncoder() );
		private var player:WavSound;
		private var _state:Boolean;
		private var _display:TextField = new TextField();
		private var _file:FileReference = new FileReference();
		
		public function TestRecorder()
		{
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}

		private function onAddedToStage(event:Event):void
		{
			_display.selectable = false;
			_display.text = "Click anywhere to initiate recording";
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			_display.autoSize = TextFieldAutoSize.LEFT;
			addChild(_display);
			recorder.addEventListener(RecordingEvent.RECORDING, onRecording);
			recorder.addEventListener(Event.COMPLETE, onRecordComplete);
			stage.addEventListener(MouseEvent.CLICK, onClick);	
		}

		private function onRecording(event:RecordingEvent):void
		{
			_display.text = "Recording since : " + event.time + " ms.";
		}

		private function onRecordComplete(event:Event):void
		{
			_display.text = "Playing recorded sound.";
			player = new WavSound(recorder.output);
			player.play();
			_file.save( recorder.output, "recorded.wav" );
		}

		private function onClick(event:MouseEvent):void
		{
			if ( !_state )
				recorder.record();
			else recorder.stop();
			
			_state = !_state;
		}
	}
}